#include "mesh.h"
#include <stdlib.h>
#include <sstream>

bool Mesh::onLoad(const char* filename){
  //Open the mesh file
  ifstream file(filename);
  if(!file.is_open()){
    return false;
  }

  //Reading the mesh file
  cout << "loading " << filename << "....";
  string line;
  while(file.good()){
    getline(file , line);
    if(line.size() > 0  && line[0] == 'f' )
      addFace(line);
    else if(line.size()>1)
      if(line[0] == 'v' && line[1] != 'n')
	addVertex(line);
  }
  cout << "done" << endl;
	
	return true;

}

void Mesh::addVertex(string line){

  vector<string> fields = split(line,' ');
  double x = 0,y =0, z=0;

  //Parsing de la valeur dans line
  x = atof(fields[1].c_str());
  y = atof(fields[2].c_str());
  z = atof(fields[3].c_str());

  //Ajout d'un point
  points.push_back(Point(x,y,z , points.size()));
}

void Mesh::addFace(string line){

  vector<string> fields = split(line,' ');
  int u = 0,v =0, w=0;

  //Parsing de les valeurs dans line
  u = atoi( split(fields[1],'/')[0].c_str() )-1;
  v = atoi( split(fields[2],'/')[0].c_str() )-1;
  w = atoi( split(fields[3],'/')[0].c_str() )-1;

  //Ajout d'une face
  Face nf( &points[u] ,   &points[v] ,  &points[w]);
   faces.push_back(nf);
   points[u].addFace(nf);
   points[v].addFace(nf);
   points[w].addFace(nf);

}

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while(getline(ss, item, delim)) {
		if(item!="")
			elems.push_back(item);
    }
    return elems;
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    return split(s, delim, elems);
}

void Mesh::print(){
  for(int i = 0 ; i < faces.size() ; i++){
    faces[i].print();
  }
}
